package com.imax.center.service.impl;

import com.imax.center.service.MinioService;
import com.imax.center.utils.MyFileUtils;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * 功能描述：外部使用
 */
@Service
@Slf4j
public class MinioServiceImpl implements MinioService {
    @Value("${minio.endpoint}")
    private String ENDPOINT;
    @Value("${minio.bucketName}")
    private String BUCKET_NAME;
    @Value("${minio.accessKey}")
    private String ACCESS_KEY;
    @Value("${minio.secretKey}")
    private String SECRET_KEY;

    private static MinioClient minioClient;

    //创建一个MinIO的Java客户端
    public void buildMinioClient() throws Exception {
        synchronized (MinioClient.class) {
            if (minioClient == null) {
                minioClient = MinioClient.builder().endpoint(ENDPOINT).credentials(ACCESS_KEY, SECRET_KEY).build();
                createBucketIfNotExists(BUCKET_NAME);
            }
        }
    }

    @Override
    public String upload(MultipartFile file) throws Exception {
        String objectName = MyFileUtils.getUuidFileName(file.getOriginalFilename());
        return upload(file, objectName);
    }

    @Override
    public String upload(MultipartFile file, String objectName) throws Exception {
        buildMinioClient();
        // 使用putObject上传一个文件到存储桶中
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(BUCKET_NAME)
                .object(objectName)
                .contentType(file.getContentType())
                .stream(file.getInputStream(), file.getSize(), ObjectWriteArgs.MIN_MULTIPART_SIZE).build();
        if (minioClient != null) {
            minioClient.putObject(putObjectArgs);
        }
        return objectName;
    }

    @Override
    public InputStream download(String objectName) throws Exception {
        buildMinioClient();
        // 使用getObject从存储桶中下载一个文件
        GetObjectArgs getObjectArgs = GetObjectArgs.builder().bucket(BUCKET_NAME).object(objectName).build();
        return minioClient.getObject(getObjectArgs);
    }

    @Override
    public void deleteFile(String objectName) throws Exception {
        buildMinioClient();
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(BUCKET_NAME).object(objectName).build());
    }

    public void createBucketIfNotExists(String bucketName) throws Exception {
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

}
